//
//  Utils.swift
//  TBCode
//
//  Created by nexgo on 2017/11/1.
//  Copyright © 2017年 truth. All rights reserved.
//

import UIKit

class Utils: NSObject {
    // data转16进制字符串
    class func data2HexString(data:Data!) -> String{
        var ret = "";
        
        for i in 0...data.count{
            ret.append(Utils.uint82HexString(value: data[i]));
        }
        return ret;
    }
    
    // data转16进制字符串带填充
    class func data2HexStringWithSpace(data:Data!, separ:String) -> String{
        var ret = "";
        
        for i in 0..<data.count{
            ret.append(Utils.uint82HexString(value: data[i]));
            if(i != (data.count-1)){
                ret.append(separ);
            }
        }
        return ret;
    }
    
    class func uint82HexString(value: UInt8) -> String{
        return String.init(format: "%02X", arguments: [value]);
    }
    
    // 16进制字符串转Data
    class func hexString2Data(hexString:String) -> Data{
        
        var tmpStr = String(hexString);

        tmpStr = tmpStr.replacingOccurrences(of: "0x", with: "");   // 先把0x这类字符串去掉
        
        var tmpStrData2 = Data();
        
        let tmpStrData = tmpStr.uppercased().data(using: String.Encoding.utf8);  // 删除非16进制字符
        
        for i in tmpStrData!{
            if(((i>=0x30) && (i<=0x39)) || ((i>=0x41) && (i<=0x46))){
                tmpStrData2.append(i);
            }
        }
        
        if(tmpStrData2.count % 2 != 0){  // 如果不是偶数的话，最后在添一个0
            tmpStrData2.append(0x30);
        }
        
        var ret = Data(count: tmpStrData2.count/2);
        
        for i in 0..<(tmpStrData2.count/2){  // 开始转换
            ret[i] = (Utils.ascii2Int(value: tmpStrData2[i*2]) << 4) | Utils.ascii2Int(value: tmpStrData2[i*2+1]);
        }
        
        return ret;
    }
    
    // ascii字符转Int
    class func ascii2Int(value:UInt8) -> UInt8{
        if((value>=0x30) && (value<=0x39)){  // 0-9
            return (value-0x30);
        }
        if((value>=0x41) && (value<=0x46)){   // A-F
            return (value-0x41+10);
        }
        
        if((value>=0x61) && (value<=0x66)){   // a-f
            return (value-0x61+10);
        }
        
        return 0;  // 非16进制数据
    }
    
}
